package com.lz.service.file.service.impl;

import com.lz.service.file.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;

@Service
public class FileServiceImpl implements FileService {

    private static final String UPLOAD_PATH = "D:/upload/";

    @Override
    public String saveFile(MultipartFile file) {
        File file1 = new File(UPLOAD_PATH);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        if (!file.getOriginalFilename().contains(".")) {
            return "文件格式不正确";
        }
        if (file.getSize() == 0) {
            return "文件大小为0";
        }
        //存放在本地
        try {
            String fileName = file.getOriginalFilename();
            String filePath = UPLOAD_PATH + fileName;
            file.transferTo(new File(filePath));
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }

    }

    @Override
    public void dowloadFile(String fileName, HttpServletResponse response) {
        //下载路径
        String path = UPLOAD_PATH + fileName;
        //文件名
        //设置响应头
        try {
            //获取输入流
            java.io.InputStream in = new java.io.FileInputStream(path);
            //获取输出流
            java.io.OutputStream out = new java.io.BufferedOutputStream(response.getOutputStream());
            //设置响应头
            response.reset();
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(path + fileName, "UTF-8"));
            //循环写入输出流
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            //关闭输入输出流
            in.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String test() {
//        try {
//            Connection connection = SQLServerConnectionTest.getConnection();
//            if (connection != null) {
//                    System.out.println("成功连接到SQL Server数据库！");
//
//                    // 获取特定视图的数据并封装到VO对象中
//                    String viewName = "V_称重信息"; // 视图名称
//                    List<DeliveryEntity> viewDataByLz = getViewDataByLz(connection, viewName);
//
//                    // 打印封装后的数据
//                    for (DeliveryEntity vo : viewDataByLz) {
//                        System.out.println(vo);
//                    }
//                }
//            } catch (SQLException e) {
//                System.err.println("连接SQL Server数据库失败！");
//                e.printStackTrace();
//            }
//
        return "success";
    }
}
